package com.ch.android.lookforkotlinv2.activity

import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.SurfaceView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.ch.android.baselib.SpUtil
import com.ch.android.baselib.SpUtil.getSessionId
import com.ch.android.baselib.SpUtil.getUserId
import com.ch.android.lookforkotlinv2.AppConst
import com.ch.android.lookforkotlinv2.R
import com.ch.android.lookforkotlinv2.databinding.ActivityLiveBinding
import com.ch.android.networklib.RequestClient
import com.ch.android.networklib.data.OpenLiveData
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.video.VideoCanvas
import kotlinx.coroutines.launch

class LiveActivity : AppCompatActivity() {
    companion object {
        private const val LIVE_DATA = "liveData"
        fun startActivity(context: Context, liveData: OpenLiveData) {
            val intent = Intent(context, LiveActivity::class.java)
            intent.putExtra(LIVE_DATA, liveData)
            context.startActivity(intent)
        }
    }
    private val mOpenLiveData by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra(LIVE_DATA, OpenLiveData::class.java)!!
        } else {
            intent.getParcelableExtra(LIVE_DATA)!!
        }
    }
    private val mBinding by lazy {
        DataBindingUtil.setContentView<ActivityLiveBinding>(this, R.layout.activity_live)
    }

    private var hasJoinChannelSuccess = false

    /**
     * Agora Rtc Engine 声网引擎
     */
    private lateinit var mRtcEngine: RtcEngine

    /**
     * 声网SDK回调
     */
    private val mRtcEventHandler: IRtcEngineEventHandler = object : IRtcEngineEventHandler() {
        override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) {
            if (hasJoinChannelSuccess) {
                return
            }
            hasJoinChannelSuccess = true
            lifecycleScope.launch {
                // 通知BW服务器，开始推流
                val resultData = RequestClient.getApiService(this@LiveActivity).startPushStream(
                    SpUtil.getSP().getSessionId(),
                    mOpenLiveData.liveData.liveId.toInt()
                )
                Log.d("LiveActivity", "startPushStream resultData: $resultData")
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!intent.hasExtra(LIVE_DATA)) {
            Toast.makeText(this, "数据传递错误", Toast.LENGTH_SHORT).show()
            finish()
        } else {
            mBinding.lifecycleOwner = this
            initAndJoinChannel()
        }
    }
    /**
     * 初始化RtcEngine
     */
    private fun initAndJoinChannel() {
        // 设置音士频的参数
        try {
            mRtcEngine = RtcEngine.create(this.baseContext, AppConst.AGORA_APP_ID, mRtcEventHandler)
            mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING)
            // 根据场景设置用户角色为：BROADCASTER（主播） 或 AUDIENCE（观众）。
            mRtcEngine.setClientRole(Constants.CLIENT_ROLE_BROADCASTER)

            // 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象。
            val surfaceView = SurfaceView(this)
            mBinding.fullscreenVideoContainer.addView(surfaceView)
            // 将 SurfaceView 对象传入 Agora，以渲染本地视频。
            mRtcEngine.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))
            val userId = SpUtil.getSP().getUserId()
            mRtcEngine.joinChannel(mOpenLiveData.liveData.agoraToken, mOpenLiveData.liveData.channelName, "", userId)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}